<?php

namespace App\Models\OpenShop\Common;

use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ShopArchiveModel extends BaseModel
{
    protected $table = 'shop_archive';

    protected $fillable = [
        'shopId',
        'businessLicense',
        'businessLicenseStartDate',
        'businessLicenseEndDate',
        'foodBusinessLicense',
        'foodBusinessLicenseStartDate',
        'foodBusinessLicenseEndDate',
    ];

    const FOREVER_DATE = '9999-12-31';  // 永久有效日期

    const  RESOURCE_BUSINESS_IMG      = 'businessLicenseImg';//营业执照img
    const  RESOURCE_FOOD_BUSINESS_IMG = 'foodBusinessLicenseImg';//食品经营许可证img

    /**
     * 根据shopId查询详情
     * @param $shopId
     * @return Builder|Model|object|null
     */
    public static function getInfoByShopId($shopId)
    {
        return self::query()->with('resourcesRel')->where(['shopId' => $shopId])->first();
    }

    /**
     * 新增
     * @param array $data
     * @return Builder|Model
     */
    public static function addShopArchive(array $data)
    {
        return self::query()->create($data);
    }

    /**
     * 修改
     * @param $id
     * @param $data
     * @return int
     */
    public static function setShopArchiveById($id, $data): int
    {
        return self::query()->where(['id' => $id])->update($data);
    }

    /**
     * 关联资源表
     * @return HasMany
     */
    public function resourcesRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId', 'id')
            ->where('module', ResourcesModel::MODULE_TYPE_SHOP)
            ->where('business', ResourcesModel::BUSINESS_SHOP_ARCHIVE)
            ->whereIn('name', [self::RESOURCE_BUSINESS_IMG, self::RESOURCE_FOOD_BUSINESS_IMG]);
    }
}
